package main

import (
	"dmsv/agent"
	"dmsv/aliyun"
	"dmsv/callrouter"
	"dmsv/common"
	"dmsv/ctgw"
	"dmsv/database"
	"dmsv/etc"
	"dmsv/models"
	"dmsv/msg"
	"dmsv/process"
	"dmsv/queue"
	"dmsv/reqcache"
	_ "dmsv/routers"
	"dmsv/session"
	"dmsv/sipuser"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/task"
	"os"
	"time"
)

const (
	task_run_per_30_seconds = "*/30 * * * * *"
	//task_run_per_30_seconds = "*/1 * * * * *" //for test myself
)

func main() {

	if beego.BConfig.RunMode == "dev" {
		beego.BConfig.WebConfig.DirectoryIndex = true
		beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
	}

	err := logs.SetLogger(logs.AdapterFile, `{"filename":"./logs/dmsv.log","maxdays":30}`)
	if err != nil {
		logs.Error("create file adapter err:%v", err)
		panic("log fail")
	}

	if beego.BConfig.RunMode != "prod" {
		/*
				//测试nacos
				nameSpaceId, _ := beego.AppConfig.String("NameSpaceId")
				addr, _ := beego.AppConfig.String("nacosAddr")
				port, _ := beego.AppConfig.Int64("nacosPort")
				err := nacos.NacosInit(beego.BConfig.RunMode, nameSpaceId, addr, uint64(port))


			if err != nil {
		*/
		if true {
			//配置文件
			err = etc.InitConfig("conf/config.yml")
			if err != nil {
				logs.Error("配置文件加载失败: %v", err)
				os.Exit(1)
			}
		}
	} else {
		//配置文件
		err := etc.InitConfig("conf/config.yml")
		if err != nil {
			logs.Error("init config failed: %v", err)
			os.Exit(1)
		}
	}

	logs.Info("mod[%v] starting...", beego.BConfig.RunMode)

	aliyun.Init()
	//模块注册
	models.RegisterModels()
	models.RegisterStatus(etc.Conf.Base.Dsid)

	//mysql初始化
	err = database.InitMysql(etc.Conf.Mysql.MysqlDBs.User,
		etc.Conf.Mysql.MysqlDBs.Password,
		etc.Conf.Mysql.MysqlDBs.IP,
		etc.Conf.Mysql.MysqlDBs.Db,
		etc.Conf.Mysql.MysqlDBs.Port,
		etc.Conf.Mysql.Debug)
	if err != nil {
		logs.Warn("mysql connect err:%v", err)
	}

	//redis信息 支持多服务器节点
	agent.RedisInit(etc.Conf.Redis.IP, etc.Conf.Redis.Password, etc.Conf.Fs.Domain)

	//设置日志层级
	logs.SetLogFuncCall(true)

	//回调发送模块
	ctgw.Init()

	//cache
	reqcache.Init()

	//路由信息
	callrouter.Init(etc.Conf.Vos.Addr)

	err = session.SessionInit(etc.Conf.Base.CallBack, etc.Conf.Fs.Addr, etc.Conf.Fs.Passwd)
	if err != nil {
		os.Exit(2)
	}

	common.Init(etc.Conf.Base.Media)
	process.Init(etc.Conf.Base.CallBack, etc.Conf.Base.Dsid)

	process.SetPreix(etc.Conf.Vos.Prefix.Notify,
		etc.Conf.Vos.Prefix.Verify,
		etc.Conf.Vos.Prefix.CallBack,
		etc.Conf.Vos.NeedPrefxi)

	//呼叫绑定关系
	process.CacheCllientInit(etc.Conf.Redis.IP, etc.Conf.Redis.Password)

	//排队机
	queue.Init()

	//状态更新任务
	//t := task.NewTask("updateStatus", task_run_per_30_seconds, statusUpdateTask)
	//task.AddTask("updateStatus", t)

	//启动任务
	task.StartTask()

	//sip用户管理模块
	sipuser.Init()

	time.Sleep(2 * time.Second)

	//恢复运行数据
	Reload()

	// 消息同步redis
	msg.Init(etc.Conf.Redis.Password, etc.Conf.Redis.IP, etc.Conf.Fs.Domain, etc.Conf.Base.Dsid)

	beego.Run()
}
